package gui.popup;

import gui.App;
import gui.dialogs.Confirm;
import gui.table.AutoTable;
import models.Client;
import models.Subscription;
import models.Workshop;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

public class SubscriptionPopup_selectWorkshop extends Popup<Subscription>{
	
	private AutoTable<Workshop> workshopTable;

	public SubscriptionPopup_selectWorkshop(App app) {
		super(app);
	}
	
	/**
	 * This function opens a subscription popup where the client is already selected. 
	 * @param client a client that you want to subscribe for a workshop.
	 * @return if the popup is filled with valid data the return is an subscription. Else this functions return <code>null</code>.
	 */
	public Subscription open_selectWorkshop(Client client) {
		Subscription subscription = open_Add();
		if (subscription != null && client != null) {
			subscription.setClient(client);
			return subscription;
		}
		return null;		
	}

	@Override
	public Subscription createEmptyModel() {
		return new Subscription();
	}

	/**
	 * this function builds the form to subscribe a client for a workshop. It calls all pieces of the popup to create the whole popup.
	 */
	@Override
	public void buildForm(Composite formPanel, Subscription subscription) {
		setTitle_modelType("Inschrijving");
		
		formPanel.setLayout(new GridLayout(2, false));

		createFormItem_label(formPanel, "Workshop");
		workshopTable = createFormItem_workshop(formPanel, subscription.getWorkshop());
	}

	/**
	 * This function checks if the workshop has reached its maximum capacatie. if the maximum is reached a warning popup is showed.
	 */
	@Override
	public boolean isDataValid() {
		Workshop workshop = workshopTable.getSelected();
		if (workshop == null) {
			alertInvalidData("Selecteer een workshop.");
			return false;
		}
		int subscriptions = getApp().getSubscriptionList().getSubscriptions(workshop).size();
		if (subscriptions >= workshop.getParticipantsMax()) {
			boolean cont = new Confirm(getShell(), 
				"Maximumcapaciteit bereikt", 
				"De maximumcapaciteit van deze workshop is reeds bereikt " +
						"(" + workshop.getParticipantsMax() + "). Toch doorgaan?"
			).open().accepted;
			if (!cont) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void updateModel(Subscription subscription) {
		subscription.setWorkshop(workshopTable.getSelected());
	}
	
}
